package me.goldze.mvvmhabit.binding.viewadapter.viewgroup;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;

import java.util.Collection;

import me.tatarka.bindingcollectionadapter2.ItemBinding;

/**
 * Created by goldze on 2017/6/18.
 */
public final class ViewAdapter {
    @BindingAdapter(value = {"itemView", "observableList", "bindOther"}, requireAll = false)
    public static void addViews(ViewGroup viewGroup, final ItemBinding itemBinding, final Collection viewModelList, IBindingItemViewModel dataBinding) {
        if (viewModelList != null && !viewModelList.isEmpty()) {
            viewGroup.removeAllViews();
            for (Object viewModel : viewModelList) {
                ViewDataBinding binding = DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()),
                        itemBinding.layoutRes(), viewGroup, true);
                int variableId = itemBinding.variableId();
                if (variableId != 0) {
                    binding.setVariable(variableId, viewModel);
                }
                if (dataBinding != null) {
                    dataBinding.injectDataBinding(binding, viewModel);
                }
            }
        }
    }
}
